<template>
    <el-card>
        <template #header>
            <h2>菜单管理</h2>
        </template>
        <div class="action-buttons">
            <el-button @click="openCreateDialog">新增菜单</el-button>
        </div>
        <el-table :data="menus" stripe>
            <el-table-column prop="name" label="菜单名称"></el-table-column>
            <el-table-column prop="url" label="菜单链接"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="openDeleteDialog(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 修正后的新增菜单对话框 -->
        <el-dialog v-model="createDialogVisible" title="新增菜单" width="20%">
            <el-form :model="newMenu" ref="createFormRef" label-width="80px">
                <el-form-item label="菜单名称" prop="name">
                    <el-input v-model="newMenu.name"></el-input>
                </el-form-item>
                <el-form-item label="菜单链接" prop="url">
                    <el-input v-model="newMenu.url"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="createDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="createMenu">确定</el-button>
            </template>
        </el-dialog>

        <!-- 修正后的编辑菜单对话框 -->
        <el-dialog v-model="editDialogVisible" title="编辑菜单" width="20%">
            <el-form :model="editMenu" ref="editFormRef" label-width="80px">
                <el-form-item label="菜单名称" prop="name">
                    <el-input v-model="editMenu.name"></el-input>
                </el-form-item>
                <el-form-item label="菜单链接" prop="url">
                    <el-input v-model="editMenu.url"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="updateMenu">确定</el-button>
            </template>
        </el-dialog>

        <!-- 修正后的删除确认对话框 -->
        <el-dialog v-model="deleteDialogVisible" title="确认删除" width="20%">
            <el-form :model="deleteForm" ref="deleteFormRef" label-width="80px">
                <el-form-item label="密码" prop="password">
                    <el-input v-model="deleteForm.password" type="password"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="deleteDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmDelete">确定</el-button>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { menuApi } from '../../api/menuApi'; // 导入封装好的API

interface Menu {
    id: number;
    name: string;
    url: string;
}

// 响应式数据
const menus = ref<Menu[]>([]);
const createDialogVisible = ref(false);
const newMenu = ref<Omit<Menu, 'id'>>({ name: '', url: '' });
const editDialogVisible = ref(false);
const editMenu = ref<Menu>({ id: 0, name: '', url: '' });
const deleteDialogVisible = ref(false);
const deleteForm = ref({ password: '' });
const deleteMenuId = ref<number | null>(null);

// 菜单操作逻辑
const fetchMenus = async () => {
    try {
        menus.value = await menuApi.fetchMenus();
    } catch (error) {
        ElMessage.error('获取菜单列表失败');
        console.error('Error fetching menus:', error);
    }
};

const openCreateDialog = () => {
    createDialogVisible.value = true;
    newMenu.value = { name: '', url: '' };
};

const createMenu = async () => {
    try {
        const createdMenu = await menuApi.createMenu(newMenu.value);
        menus.value.push(createdMenu);
        createDialogVisible.value = false;
        ElMessage.success('菜单创建成功');
    } catch (error) {
        ElMessage.error('菜单创建失败');
        console.error('Error creating menu:', error);
    }
};

const openEditDialog = (menu: Menu) => {
    editDialogVisible.value = true;
    editMenu.value = { ...menu };
};

const updateMenu = async () => {
    if (!editMenu.value.id) return;

    try {
        await menuApi.updateMenu(editMenu.value.id, {
            name: editMenu.value.name,
            url: editMenu.value.url
        });
        const index = menus.value.findIndex(m => m.id === editMenu.value.id);
        if (index !== -1) {
            menus.value[index] = { ...editMenu.value };
        }
        editDialogVisible.value = false;
        ElMessage.success('菜单更新成功');
    } catch (error) {
        ElMessage.error('菜单更新失败');
        console.error('Error updating menu:', error);
    }
};

const openDeleteDialog = (id: number) => {
    deleteDialogVisible.value = true;
    deleteMenuId.value = id;
    deleteForm.value.password = '';
};

const confirmDelete = async () => {
    if (!deleteMenuId.value) return;

    try {
        // 实际项目中建议使用更安全的鉴权方式
        const storedPassword = localStorage.getItem('password');
        if (deleteForm.value.password !== storedPassword) {
            throw new Error('密码验证失败');
        }

        await menuApi.deleteMenu(deleteMenuId.value);
        menus.value = menus.value.filter(m => m.id !== deleteMenuId.value);
        deleteDialogVisible.value = false;
        ElMessage.success('菜单删除成功');
    } catch (error) {
        ElMessage.error(error instanceof Error ? error.message : '删除操作失败');
        console.error('Error deleting menu:', error);
    }
};

onMounted(() => {
    fetchMenus();
});
</script>

<style scoped lang="scss">
.action-buttons {
    margin-bottom: 20px;
}

:deep(.el-dialog) {
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
    margin: 0 !important;
    border-radius: 10px;
}
</style>